package com.aiti.lulian.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CustomerTagDto;
import com.aiti.lulian.entity.CustomerTag;
import com.aiti.lulian.entity.CustomerTagGroup;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CustomerTagGroupMapper;
import com.aiti.lulian.mapper.CustomerTagMapper;
import com.aiti.lulian.service.ICustomerTagService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CustomerTagServiceImpl extends BaseSerivceImpl<CustomerTagMapper, CustomerTag> implements ICustomerTagService {

    private final CustomerTagGroupMapper customerTagGroupMapper;

    private CloudShowManagerSubService cloudShowManagerSubService;

    public CustomerTagServiceImpl(CustomerTagGroupMapper customerTagGroupMapper, CloudShowManagerSubService cloudShowManagerSubService) {
        this.customerTagGroupMapper = customerTagGroupMapper;
        this.cloudShowManagerSubService = cloudShowManagerSubService;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message addOrUpdateTag(CustomerTagDto customerTagDto) {
        CustomerTag customerTag = new CustomerTag();
        BeanUtils.copyProperties(customerTagDto, customerTag);
        if (StrUtil.isBlank(customerTagDto.getBaseId())) {
            //新增标签
            customerTag.setCreator(customerTagDto.getUserId());
            customerTag.setBaseCreateTime(new Date());
        } else {
            //标记标签
            customerTag.setUpdateBy(customerTagDto.getUserId());
            customerTag.setBaseUpdateTime(new Date());
        }
        boolean saveOrUpdate = this.saveOrUpdate(customerTag);
        //更新标签组相关数据
        int update = customerTagGroupMapper.update(null, new LambdaUpdateWrapper<CustomerTagGroup>().eq(CustomerTagGroup::getBaseId, customerTagDto.getTagGroupId())
                .set(CustomerTagGroup::getUpdateBy, customerTagDto.getUserId())
                .set(CustomerTagGroup::getBaseUpdateTime, new Date()));
        if (saveOrUpdate && (update > 0)) {
            return Message.success("操作成功");
        } else {
            return Message.fail("操作失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message deleteTag(CustomerTagDto customerTagDto) {
        //删除标签
        boolean remove = this.removeById(customerTagDto.getBaseId());
        //更新标签组相关数据
        int update = customerTagGroupMapper.update(null, new LambdaUpdateWrapper<CustomerTagGroup>().eq(CustomerTagGroup::getBaseId, customerTagDto.getTagGroupId())
                .set(CustomerTagGroup::getUpdateBy, customerTagDto.getUserId())
                .set(CustomerTagGroup::getBaseUpdateTime, new Date()));
        if (remove && (update > 0)) {
            return Message.success("删除成功");
        } else {
            return Message.fail("删除失败");
        }
    }

    @Override
    public Message getTagList(CustomerTagDto customerTagDto) {
        //获取当前用户的权限
        String scope;
        String userId = customerTagDto.getUserId();
        Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(userId);
        if (userAccessScopeMessage == null) {
            throw new RuntimeException("获取用户访问权限失败");
        } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
            throw new RuntimeException("查询用户访问权限失败");
        } else {
            scope = (String) userAccessScopeMessage.getObj();
            List<CustomerTag> tagList = new ArrayList<>();
            if (StrUtil.equals(scope, "4")) {
                //企业管理员
                tagList = this.list(new LambdaQueryWrapper<CustomerTag>().eq(CustomerTag::getTagGroupId, customerTagDto.getTagGroupId()));
            } else {
                tagList = this.list(new LambdaQueryWrapper<CustomerTag>()
                        .nested(i -> i.eq(CustomerTag::getCreator, userId).or().eq(CustomerTag::getIsPublic, "1"))
                        .eq(CustomerTag::getTagGroupId, customerTagDto.getTagGroupId()));
            }
            return Message.success(tagList);
        }
    }

    @Override
    public Message getTagDetails(String baseId) {
        CustomerTag tag = this.getById(baseId);
        return Message.success(tag);
    }

    @Override
    public List<CustomerTag> getList(String scope, String userId, String groupId) {
        return baseMapper.selectTagListByScope(scope, userId, groupId);
    }

    @Override
    public Message getTags(CustomerTagDto customerTagDto) {
        //获取当前用户的权限
        String scope;
        String userId = customerTagDto.getUserId();
        Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(userId);
        if (userAccessScopeMessage == null) {
            throw new RuntimeException("获取用户访问权限失败");
        } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
            throw new RuntimeException("查询用户访问权限失败");
        } else {
            scope = (String) userAccessScopeMessage.getObj();
            customerTagDto.setScope(scope);
            List<CustomerTag> customerTags = baseMapper.selectTags(customerTagDto);
            return Message.success(customerTags);
        }
    }
}